package com.auth.manage.base.util.sharding.id;

import cn.hutool.core.util.IdUtil;
import com.auth.manage.base.util.sharding.constant.BusinessCode;
import com.auth.manage.base.util.sharding.strategy.DefaultShardingTableStrategy;
import org.apache.commons.lang3.StringUtils;

public class DistributeID {

    /**
     * 生成一个唯一ID：10（业务码） 1769649671860822016（sequence) 1023(分表）
     */
    public static String generate(BusinessCode businessCode, long workerId,String externalId){
        // 1.雪花算法计算出唯一id
        long id = IdUtil.getSnowflake(workerId).nextId();  // workerId：机器id
        // 2.根据外部id，计算出表下标
        int table = DefaultShardingTableStrategy.getTableIndex(externalId, businessCode.getTableCount());
        String tableIndex = StringUtils.leftPad(String.valueOf(table), 4, "0");  // 123 -> 0123 1234 -> 1234 12 -> 0012
        // 3.拼接
        return businessCode.getCode() + id + tableIndex;
    }

}
